//
//  UWFriendDetailHistory.m
//  Urban Words
//
//  Created by sebastian on 2011-12-09.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "UWFriendDetailHistory.h"
#import <QuartzCore/CALayer.h>
#import "UILabel+UW.h"
#import "UWFriendManager.h"
#import "UWHistoryManager.h"

// Private TableViewController properties and methods.
@interface UWFriendDetailHistory ()

@property (nonatomic, strong) NSMutableArray *sectionInfoArray;
@property (nonatomic, assign) NSInteger openSectionIndex;

@end

@implementation UWFriendDetailHistory

@synthesize sectionInfoArray, openSectionIndex;
@synthesize friend;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil friend:(UWFriend *)fr
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //self.title = NSLocalizedString(@"History", @"History");
        //self.tabBarItem.image = [UIImage imageNamed:@"first"];
        //self.tableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"uw-tableview-background.png"]];
        self.tableView.separatorColor = [UIColor clearColor];
        self.title = fr.name;
        test = YES;
        allCells = [[NSMutableArray alloc] init];
        //manager = [[UWHistoryManager alloc] initFriendHistoryWithFriend:@"646545990" delegate:self];
        //manager = [[UWHistoryManager alloc] initGameHistoryWithGameid:@"11" delegate:self];
        friend = fr;
        manager = [[UWHistoryManager alloc] initFriendHistoryWithFriend:fr.fid delegate:self];
        friendDetail = [[UWFriendDetail alloc] initWithFriend:fr];
        openSectionIndex = NSNotFound;
        self.tableView.frame = CGRectMake(0, 100, 320, 100);
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    // Name in navBar
    UIView *labelContainer = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 200, 30)];
    labelContainer.backgroundColor = [UIColor clearColor];
    //UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 6, 200, 30)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    [label setSpecialText:friend.name];
    [labelContainer addSubview:label];
    self.navigationItem.titleView = labelContainer;
    [label release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [friendDetail viewDidAppear];
    
   // [self scrollToBottom];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [manager count]+1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section==0) {
        return 0;
    } else {
        UWHistoryCell *tmp = [manager getHeaderAtSection:(section-1)];
        return tmp.open?1:0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //NSLog(@"%f", [[self tableView:tableView cellForRowAtIndexPath:indexPath] frame].size.height);
    //NSLog(@"%f", [tmp getRowHeight]);
    return [[manager getHeaderAtSection:(indexPath.section-1)] getExplanation ].frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"cellForRow: %i", indexPath.section-1);
    UILabel *exp = [manager getDefFromHeaderAtSection:(indexPath.section-1)];
    UIView *tmp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, exp.frame.size.height)];
    [tmp addSubview:exp];
    tmp.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSLog(@"cellForRow: %@", exp.text);
    [cell addSubview:exp];
    [tmp release];
    [exp release];
    return cell;
}

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {
    
    /*
     Create the section header views lazily.
     */
    if (section==0) {
        NSLog(@"friend detail");
        return friendDetail;
    } else {
        NSLog(@"section: %i", section);
        return [manager getHeaderAtSection:(section-1)];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0 ) {
        return friendDetail.frame.size.height;
    } else {
        return [manager rowheightForHeaderAtSection:(section-1)];
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

#pragma mark Section header delegate

-(void)sectionHeaderView:(UWHistoryCell*)sectionHeaderView sectionOpened:(NSInteger)sectionOpened {
	NSLog(@"sectionOpened: %i",sectionOpened);
	UWHistoryCell *openCell = [manager getHeaderAtSection:sectionOpened];
	
	openCell.open = YES;
    //sectionHeaderView.open = YES;
    /*
     Create an array containing the index paths of the rows to insert: These correspond to the rows for each quotation in the current section.
     */
    NSInteger countOfRowsToInsert = 1;
    NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < countOfRowsToInsert; i++) {
        [indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:sectionOpened+1]];
    }
    
    /*
     Create an array containing the index paths of the rows to delete: These correspond to the rows for each quotation in the previously-open section, if there was one.
     */
    NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
    
    NSInteger previousOpenSectionIndex = self.openSectionIndex;
    if (previousOpenSectionIndex != NSNotFound) {
		
		UWHistoryCell *previousOpenCell = [manager getHeaderAtSection:previousOpenSectionIndex];
        previousOpenCell.open = NO;
        NSInteger countOfRowsToDelete = 1;
        for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
            [indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:previousOpenSectionIndex+1]];
        }
    }
    
    NSLog(@"Begin animation");
    // Style the animation so that there's a smooth flow in either direction.
    UITableViewRowAnimation insertAnimation;
    UITableViewRowAnimation deleteAnimation;
    if (previousOpenSectionIndex == NSNotFound || sectionOpened < previousOpenSectionIndex) {
        insertAnimation = UITableViewRowAnimationTop;
        deleteAnimation = UITableViewRowAnimationBottom;
    }
    else {
        insertAnimation = UITableViewRowAnimationBottom;
        deleteAnimation = UITableViewRowAnimationTop;
    }
    
    // Apply the updates.
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:deleteAnimation];
    [self.tableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:insertAnimation];
    [self.tableView endUpdates];
    self.openSectionIndex = sectionOpened;
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:sectionOpened+1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}


-(void)sectionHeaderView:(UWHistoryCell*)sectionHeaderView sectionClosed:(NSInteger)sectionClosed {
    
    /*
     Create an array of the index paths of the rows in the section that was closed, then delete those rows from the table view.
     */
	UWHistoryCell *sectionInfo = [manager getHeaderAtSection:sectionClosed];
	
    sectionInfo.open = NO;
    NSInteger countOfRowsToDelete = 1;
    
    if (countOfRowsToDelete > 0) {
        NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
            [indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:sectionClosed+1]];
        }
        [self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationTop];
    }
    self.openSectionIndex = NSNotFound;
}

- (void)scrollToBottom
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:[manager count]-1];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (void)updateTable {
    [self.tableView reloadData];
}

@end
